<?php

if (!defined('IN_AUTOSAVE')) exit('Access Denied');

function fetchURL($url, $cookie='', $ua='Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36')
{
     //处理省略协议默认用HTTP
    if (substr($url,0,2)=='//')
        $url = 'http:'.$url;

    if (defined('FETCH_USER_AGENT') && FETCH_USER_AGENT != '')
        $ua = FETCH_USER_AGENT;
    if (defined('FETCH_COOKIE') && FETCH_COOKIE != '')
        $cookie = FETCH_COOKIE;

    //开始请求
    $ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, 120);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($ch, CURLOPT_USERAGENT, $ua);
	curl_setopt($ch, CURLOPT_COOKIE, $cookie);
	$data = curl_exec($ch);
	$info = curl_getinfo($ch);
	curl_close($ch);
    unset($ch);
	return array('success'=> ($info['http_code']<400) ,'data'=>$data , 'info'=> $info);
}

function getFileName($url)
{
	$filename = substr( $url, strrpos($url, '/')+1);
    return ($filename!='')?$filename:NULL;
}

function extend_name($filename){
	return pathinfo($filename, PATHINFO_EXTENSION);
}

function addTaskData($task, $data , $now_md5)
{
    $time = date(SAVE_TIME_FORMAT,time());
    $dir = SAVE_ROOT.'/'.$task['save_dir'];
    $file = getFileName($task['url']);
	if (!$file)
		$file = 'unnamed';
    $extend_name = extend_name($file);
	if (!$extend_name)
		$extend_name = 'default';
    $file = basename($file,'.'.$extend_name).".{$time}.".$extend_name;
    file_put_contents($dir.'/'.$file, $data);
    file_put_contents($dir.'/last.md5', $now_md5);
    return $file;
}

function is_newest($task, $now_md5)
{
    $dir = SAVE_ROOT.'/'.$task['save_dir'];
    $md5_file = $dir.'/last.md5';
    if (!file_exists($md5_file))
        return false;
    $last_md5 = file_get_contents($md5_file);
    return $last_md5==$now_md5 ;
}

function execTask($task){
    $url = $task['url'];
    $dir = SAVE_ROOT.'/'.$task['save_dir'];
    $mode = $task['save_mode'];
    $result['err'] = FETCH_UNKONW_ERROR;
    if ($mode == MODE_MODIFIED)
    {
        if (! file_exists($dir) )
            mkdir($dir,0777);

        $response = fetchURL($url);
        if ($response['success']){
            $now_md5 = md5($response['data']);

            if (!is_newest($task, $now_md5))
            {
                $result['filename'] = addTaskData($task, $response['data'], $now_md5);
                $result['err'] = FETCH_SUCCESS;
            }else{
            	$result['err'] = FETCH_NOT_MODIFIED;
            }

        }else{
        $result['err'] = FETCH_FAILED;
        }

    }else{
    	$result['err'] = FETCH_NOT_SUPPORT;
    }
 	return $result;
}
?>